import { Component, OnInit, Input, ComponentRef, EventEmitter } from "@angular/core";
import { FileService } from "./file.service";
import * as _ from "lodash";
import { FileUploader } from "ng2-file-upload";
import { environment } from '../../../../../environments/environment';
import { Util } from 'app/common/util';
import { AppPaginationComponent, PaginationModel } from "../../../../widgets/pagination/pagination.component";
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { DataService } from '../../../../services/data.service';

@Component({
  selector: "app-annuity-file",
  templateUrl: "./file.component.html",
  styleUrls: ["./file.component.scss"],
  providers: [FileService]
})
export class SocialFileComponent implements OnInit {

  // 从路由获取内码
  public nFundNo: any;

  // 判断路由是否有内码，如果没有则是从列表勾选上传。
  public isFromRouter: any;

  // 是否初始化上传参数
  public isInitUploadParams: any = true;

  // 关联组合-是否关联受托人
  public isConnected: any = false;

  // 是否显示上传文件框的上传、删除文件按钮
  public showUploadBtn: any;
  // lodash
  public _: any = _;
  // 组合文件类型
  public groupFileClass = [];
  // 合同扫描
  public ContractScanning = [];
  // 合同备忘与协议
  public contractAgreement = [];
  // 账户类
  public accountClass = [];
  // 投资类
  public InvestmentClass = [];
  // 备报确认函
  public onfirmation = [];
  // 业绩考核
  public performanceAssessment = [];
  // 受托人附件
  public assignee = [];
  // 关联人员
  public Associates = [];
  // 其他
  public Other = [];

  // 初始化定义uploader变量,用来配置input中的uploader属性
  public uploader: FileUploader = new FileUploader({
    url: environment.server + "/pms/v1/pension/attach/batchFile?token=" + sessionStorage.getItem('token')

    // { key: "nFundNo", value:7611},
    // { key: "sAttachCode", value: 'zhlSBJJ' },
    // { key: "sAttachType", value: '账户类' },
    // { key: "sFundType", value: 4 }
  });
  // 上传文件的名称
  public uploadFileName: any = "";
  // 选择文件状态
  public fileStatus = false;
  // 上传文件名
  public fileName;
  // 历史附件列表
  public listAttach = [];
  // 当前激活的附件tab的code和type
  public sAttachCode: any = 'htsmSBJJ';
  public sAttachType: any = '合同扫描'

  // 保存获取到的sAttachType，用于上传文件
  public sAttachTypeArray: any = [];

  // 已选中列表数据
  public groupFilecheckedList;
  //  合同扫描
  public contractCheckboxAll = false;
  //  合同备忘与协议
  public agreementCheckboxAll = false;
  //  账户类
  public accountCheckboxAll = false;
  //  账户类
  public investmentCheckboxAll = false;
  //  报备确认函
  public confirmationCheckboxAll = false;
  //  业绩考核
  public assessmentCheckboxAll = false;
  //  业绩考核
  public otherCheckboxAll = false;
  //  关联人员
  public associatesCheckboxAll = false;
  //  受托人附件
  public enclosureCheckboxAll = false;

  // 加载基础信息的body，用于关联组合
  public associateListBody: any = {
    sTrustee: '',
    sLinkPrincipalNo: '',
    sFundCode: '',
    sFullName: '',
    statusList: ['wyz'],
    sFundType: '6'
  }

  // 关联组合body
  public makeAssociateBody: any = {
    // form.append('nFundNo', 7611),
    // form.append('sAttachCode', 'zhlSBJJ'),
    // form.append('sAttachType', '账户类'),
    // form.append('sFundType', 4),
    // form.append('sLinkPrincipalNo','gfyh'),
    // form.append('sLinkPrincipal','广发银行'),
    // form.append('linkFundNoList',arrayObject)
  }
  //关联组合分页配置
  public associateListPageInfo: PaginationModel = {
    currentPageNum: 1,
    pageSize: 5,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };

  // 关联组合列表数据
  public associateList: any;
  // 备案机构、受托人、托管人
  public distionary: any = {
    RECORDORG_TYPE: [],  // 备案机构
    LINK_PRINCIPAL_NO: [],   //受托人
    TRUSTEE: []   //  托管人
  }
  // 获取字典值
  public dictionaryList: any = {
    // TRUSTEE: [],
    // LINK_PRINCIPAL_NO: []
  };

  // 获取托管行
  // public bankDictionaryList: any;

  // 列表是否全选
  public isCheckedAll = false;

  // 关联列表勾中项
  public checkedList: any = [];

  // 关联列表勾中项副本
  public copyCheckedList: any = [];
  constructor(
    private fileService: FileService,
    private route: ActivatedRoute,
    public dataService: DataService
  ) {
    this.showUploadBtn = this.dataService.showUploadBtn
    this.route.params.subscribe((data) => {
      if (data.nFundNo) {
        this.nFundNo = data.nFundNo;
        this.isFromRouter = true;
      } else {
        this.nFundNo = this.nFundNo;
        this.isFromRouter = false;
      }
    })
  }

  ngOnInit() {
    // 解决附件跨域问题
    this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; };
    this.dictionaryList = JSON.parse(localStorage.getItem("dictionaryList"));
    this.getDictionary();
    // this.bankDictionaryList = JSON.parse(localStorage.getItem("bankDictionaryList"));
    this.loadFileTree();
  }
  // 获取上传文件名称
  selectedFileOnChanged(event: any) {
    this.uploadFileName = event.target.value;
    this.fileStatus = true;
    // 兼容ie title不出现问题
    this.fileName = event.target.value;
    console.log(this.uploader.queue)
  }

  // 上传文件
  uploadFile() {
    let that = this;
    let fileItem = this.uploader.queue;
    let linkFundNoList = [];
    _.forEach(this.checkedList, (item) => {
      linkFundNoList.push(item.nFundNo)
    })


    // 添加 POST 其他参数
    this.uploader.onBuildItemForm = (item, form) => {
      if (this.isConnected) {
        form.append('sLinkPrincipalNo', this.dataService.sLinkPrincipalNo),
          form.append('sLinkPrincipal', this.dataService.sLinkPrincipal)
      }
      form.append('nFundNo', this.nFundNo),
        form.append('sAttachCode', this.sAttachCode),
        form.append('sAttachType', this.sAttachType),
        form.append('sFundType', 6),
        form.append('linkFundNoList', linkFundNoList)
    };
    console.log(linkFundNoList);
    console.log(this.uploader.queue)
    window['swal']({
      title: "提示",
      text: "是否确定上传附件?",
      type: "warning",
      showCancelButton: true,
      closeOnConfirm: true,
      confirmButtonText: "确认",
      confirmButtonColor: "#DD6B55",
      cancelButtonText: "取消",
      html: true
    }, function (isConfirm) {
      if (isConfirm) {
        // 开始上传
        that.uploader.uploadAll();
      }
    }
    );

    // 存放已上传文件数量
    let uploadedFile = [];
    let queueCount = this.uploader.queue.length;
    let uploadFailedFile = [];
    console.log('queueCount' + queueCount)
    this.uploader.onSuccessItem = function (item, response, status, headers) {
      let responseData: any = [];
      if (response) {
        uploadedFile.push(response);
      }
      responseData = JSON.parse(response)
      // 返回状态码为0即为上传成功。
      if (responseData.code != 0) {
        uploadFailedFile.push(response);

      }
      if (uploadedFile.length == queueCount) {
        if (uploadFailedFile.length != 0) {
          setTimeout(() => {
            window["swal"]("提示", "存在上传失败文件，请检查格式", "warning");
          }, 200)
          that.isCheckedAll = false;
          that.checkedList = [];
          that.clearFileQueue();
          that.loadFileTree();
          that.dataService.sLinkPrincipalNo = '';
          that.dataService.sLinkPrincipal = '';
        } else {
          if (uploadedFile.length == that.uploader.queue.length) {
            window["swal"]("成功", "文件上传成功!", "success");
            that.isCheckedAll = false;
            that.checkedList = [];
            that.clearFileQueue();
            that.loadFileTree();
            that.dataService.sLinkPrincipalNo = '';
            that.dataService.sLinkPrincipal = '';

          }
        }
      }

      console.log(response);
      // console.log(responseData.data[0].nAttachNo);
      // if (uploadedCount.length == that.uploader.queue.length) {
      //   window["swal"]("成功", "文件上传成功!", "success");
      //   that.checkedList = [];
      //   that.clearFileQueue();
      //   that.loadFileTree();

      // } 
    };
    // 全部文件上传完成后的回调
    // this.uploader.onCompleteAll = () => {
    //   window["swal"]("成功", "文件上传成功!", "success");
    //   that.checkedList = [];
    //   that.clearFileQueue();
    //   that.loadFileTree();
    //   that.dataService.sLinkPrincipalNo = '';
    //   that.dataService.sLinkPrincipal = ''
    //   console.log('complete');
    // }
    ;

  }
  // 清除FileUploader上传队列中的所有文件
  clearFileQueue() {
    this.uploader.clearQueue();
    this.fileStatus = false;
    window['$']('#uploadModal').modal('hide');
    window["$"]("#fileInput").val("");
  }


  checkedAll() {
    if (this.isCheckedAll) { // 更新为全选
      _.forEach(this.associateList, item => {
        item.isChecked = true;
      });
    } else { // 更新为不全选
      _.forEach(this.associateList, item => {
        item.isChecked = false;
      });
    }
    this.ctrlCheckAll();
  }

  // 关联组合取消操作
  uncheckedAll() {
    console.log(this.copyCheckedList)
    this.checkedList = this.copyCheckedList;

    this.isCheckedAll = false;
    let difference = this.copyCheckedList
      .filter(x => this.checkedList.indexOf(x) == -1)
      .concat(this.checkedList.filter(x => this.copyCheckedList.indexOf(x) == -1));
    console.log(difference)
    _.forEach(this.associateList, item => {
      _.forEach(difference, it => {
        if (item.nFundNo == it.nFundNo) {
          item.isChecked = false;
        }
      })
    })
    window['$']('#associateModal').modal('hide');
    window['$']('.modal-backdrop').remove()
  }
  // 列表是否全选
  ctrlCheckAll() {
    let that = this;
    let thisPageChecked = [];

    let item = {
    }
    _.forEach(this.associateList, item => {
      let isChongfu = false;
      if (item.isChecked == true) {
        thisPageChecked.push(item);
        _.forEach(this.checkedList, it => {
          if (it.nFundNo == item.nFundNo) {
            isChongfu = true;
          }
        })
        if (!isChongfu) {
          this.checkedList.push(item);
        }
        // this.checkedList.push(item);
        // this.checkedList = _.uniq(this.checkedList);
      } else {
        this.checkedList = _.filter(this.checkedList, function (it: any) {
          return it.nFundNo != item.nFundNo;
        });

      }

    })

    if (thisPageChecked.length == this.associateList.length) {
      this.isCheckedAll = true;
    } else {
      this.isCheckedAll = false;
    }
  }

  // 点击移除已勾选组合
  removeItem(item) {
    console.log(item);
    this.checkedList = _.filter(this.checkedList, function (it) {
      return it != item
    });
    _.forEach(this.associateList, (it) => {
      if (it == item) {
        it.isChecked = false;
        this.isCheckedAll = false;
      }
    })
  }

  // 查询分页列表 加载基础信息，用于关联组合
  loadInfoList(pageNum?, pageSize?, time?) {
    this.associateList = [];
    let that = this;
    this.isCheckedAll = false;
    this.associateListBody.sFullName = _.trim(this.associateListBody.sFullName);
    this.associateListBody.sFundCode = _.trim(this.associateListBody.sFundCode);
    this.associateListBody.pageIndex = pageNum ? pageNum : this.associateListPageInfo.currentPageNum;
    this.associateListBody.pageSize = pageSize ? pageSize : this.associateListPageInfo.pageSize;
    this.fileService.associateList(this.associateListBody).subscribe(data => {
      if (data) {

        that.associateList = data.list;
        //全选保存状态
        // 如果第一次进来modal，加载之前保存的数组
        if (time == 'firstTime') {
          _.forEach(that.associateList, item => {
            // console.log(item);
            _.forEach(that.copyCheckedList, it => {
              console.log(that.copyCheckedList);
              if (it.nFundNo == item.nFundNo) {
                item.isChecked = it.isChecked
              }
            })
          })
          that.ctrlCheckAll();
        }
        // 如果列表已经初始化，换页时用临时数组保存打勾状态。
        else {
          _.forEach(that.associateList, item => {
            // console.log(item);
            _.forEach(that.checkedList, it => {
              console.log(that.checkedList);
              if (it.nFundNo == item.nFundNo) {
                item.isChecked = it.isChecked
              }
            })
          })
          that.ctrlCheckAll();
        }
        console.log(that.associateList);
        that.associateListPageInfo.currentPageNum = data.pageNum;
        that.associateListPageInfo.totalPages = data.pages;
        that.associateListPageInfo.total = data.total;
        that.associateListPageInfo.startRow = data.startRow;
        that.associateListPageInfo.endRow = data.endRow;
      }
    });
  }
  // 个数分页
  associatepageSizeChange(pageSize: number) {
    if (pageSize !== this.associateListPageInfo.pageSize) {
      this.associateListPageInfo.pageSize = pageSize;
      this.loadInfoList();
    }
  }
  // 页码分页
  associatePageNavigation(currentPageNum: number) {
    this.associateListPageInfo.currentPageNum = currentPageNum;
    this.loadInfoList(this.associateListPageInfo.currentPageNum, this.associateListPageInfo.pageSize);
  }
  // 显示上传modal
  showUploadModal() {
    // 加载基础信息列表
    this.loadInfoList(1, 5, 'firstTime');


    window['$']('.modal-backdrop').remove()
    window['$']("#uploadModal").modal('show');
  }
  // 显示关联组合modal
  showAssociate() {
    this.loadInfoList(1, 5, 'firstTime');
    // 托管人
    let that = this;
    // 运作状态多选下拉框
    let statusList: any = [
      { sItemKey: 'wyz', sItemValue: '未运作' },
      { sItemKey: 'yyz', sItemValue: '运作中' }
    ]
    setTimeout(function () {
      // 运作状态
      window['$']('#runningStatus').selectpicker('destroy');
      Util.loadSelect(statusList, 'runningStatus');
      //updated by dujh @20180627 start
      //window['$']('#runningStatus').selectpicker('val','wyz');
      window['$']('#runningStatus').selectpicker('val', ['wyz', 'yyz']);
      //updated by dujh @20180627 end

      window['$']('#filesLinkPrincipalNoSelected').select2({ width: '190px', tags:true });
      window['$']('#filesLinkPrincipalNoSelected').select2("val", "--请选择--");
      window['$']('#filesLinkPrincipalNoSelected').on("select2:select", function (e) {
        that.associateListBody.sLinkPrincipalNo = window['$']('#filesLinkPrincipalNoSelected').select2("val");
      })
      window['$']('#filesTrusteeSelected').select2({ width: '190px' });
      window['$']('#filesTrusteeSelected').select2("val", "--请选择--");
      window['$']('#filesTrusteeSelected').on("select2:select", function (e) {
        that.associateListBody.sTrustee = window['$']('#filesTrusteeSelected').select2("val");
      })
    }, 100);
    window['$']('.modal-backdrop').remove()
    window['$']("#associateModal").modal('show');
  }
  showHisListModal(item) {
    this.groupFilecheckedList = item;
    let that = this;
    if (item == "") {
      window['swal']("提示", "无历史附件", "warning");
    } else {
      this.fileService.getListAttach(item).subscribe(data => {
        if (data) {
          that.listAttach = data;
        }
      });
      window["$"]("#historyFileModal").modal('show');
    }

  }

  // 关联组合modal 确定操作
  closeAssociateModal() {
    this.copyCheckedList = [];
    this.copyCheckedList = this.checkedList;
    // _.forEach(this.associateList, item => {
    //   if (item.isChecked) {
    //     this.copyCheckedList.push(item);
    //   }
    // })
    if (this.copyCheckedList.length == 0 && !this.isConnected) {
      window['swal']("提示", "请选择关联组合", "warning");
    }
    else {
      console.log(this.copyCheckedList);
      window['$']('#associateModal').modal('hide');
      window['$']('.modal-backdrop').remove()
      window['swal']("提示", "保存成功", "success");
    }
  }

  // 加载附件树
  loadFileTree() {
    var that = this;
    let getBody = {
      sFundType: 6,
      nFundNo: this.nFundNo
    };
    // 合同扫描
    this.ContractScanning = [];
    // 合同备忘与协议
    this.contractAgreement = [];
    // 账户类
    this.accountClass = [];
    // 投资类
    this.InvestmentClass = [];
    // 备报确认函
    this.onfirmation = [];
    // 业绩考核
    this.performanceAssessment = [];
    // 受托人附件
    this.assignee = [];
    // 关联人员
    this.Associates = [];
    // 其他
    this.Other = [];
    this.fileService.getFileTree(getBody).subscribe(data => {
      if (data) {
        console.log(data);
        _.forEach(data.subTree, function (item, index) {

          that.groupFileClass.push(item.sAttachCode);
          that.sAttachTypeArray.push(item.sAttachType);
          switch (item.sAttachCode) {
            case "htsmSBJJ": //合同扫描
              _.forEach(item.fileList, function (itemT) {
                itemT['editDesc'] = '0';
                itemT['sFileDesc'] = '';
                that.ContractScanning.push(itemT);
              });
              that.ctrlCheckAll2(that.ContractScanning, 'contractCheckboxAll');
              break;
            case "htbwyxySBJJ": //合同备忘与协议
              _.forEach(item.fileList, function (itemT) {
                itemT['editDesc'] = '0';
                itemT['sFileDesc'] = '';
                that.contractAgreement.push(itemT);
              });
              that.ctrlCheckAll2(that.contractAgreement, 'agreementCheckboxAll');
              break;
            case "zhlSBJJ": // 账户类
              _.forEach(item.fileList, function (itemT) {
                itemT['editDesc'] = '0';
                itemT['sFileDesc'] = '';
                that.accountClass.push(itemT);
              });
              that.ctrlCheckAll2(that.accountClass, 'accountCheckboxAll');
              break;
            case "tzlSBJJ": //  投资类
              _.forEach(item.fileList, function (itemT) {
                itemT['editDesc'] = '0';
                itemT['sFileDesc'] = '';
                that.InvestmentClass.push(itemT);
              });
              that.ctrlCheckAll2(that.InvestmentClass, 'investmentCheckboxAll');
              break;
            case "bbqrhSBJJ": // 报备确认函
              _.forEach(item.fileList, function (itemT) {
                itemT['editDesc'] = '0';
                itemT['sFileDesc'] = '';
                that.onfirmation.push(itemT);
              });
              that.ctrlCheckAll2(that.onfirmation, 'confirmationCheckboxAll');
              break;
            case "yjkhSBJJ": // 业绩考核
              _.forEach(item.fileList, function (itemT) {
                itemT['editDesc'] = '0';
                itemT['sFileDesc'] = '';
                that.performanceAssessment.push(itemT);
              });
              that.ctrlCheckAll2(that.performanceAssessment, 'assessmentCheckboxAll');
              break;
            case "strfjSBJJ": // 受托人附件
              _.forEach(item.fileList, function (itemT) {
                itemT['editDesc'] = '0';
                itemT['sFileDesc'] = '';
                that.assignee.push(itemT);
              });
              that.ctrlCheckAll2(that.assignee, 'enclosureCheckboxAll');
              break;
            case "glrySBJJ": // 关联人员
              _.forEach(item.fileList, function (itemT) {
                itemT['editDesc'] = '0';
                itemT['sFileDesc'] = '';
                that.Associates.push(itemT);
              });
              that.ctrlCheckAll2(that.Associates, 'associatesCheckboxAll');
              break;
            case "qtSBJJ": // 其他
              _.forEach(item.fileList, function (itemT) {
                itemT['editDesc'] = '0';
                itemT['sFileDesc'] = '';
                that.Other.push(itemT);
              });
              that.ctrlCheckAll2(that.Other, 'otherCheckboxAll');
              break;
          }
        });
        if (this.isInitUploadParams) {
          this.sAttachCode = this.groupFileClass[0];
          this.sAttachType = this.sAttachTypeArray[0];
        }

      }
    });
  }
  // 下载附件
  downLoadFile(item) {
    if (item.nAttachNo) {
      Util.attachDownload([item.nAttachNo]);
    } else {
      window['swal']("提示", "请选择文件再下载", "warning");
    }
  }

  //列表全选
  checkAll(data, checkAllBox) {
    console.log(data);
    if (checkAllBox) {
      // 更新为全选
      _.forEach(data, item => {
        item.isChecked = true;
      });
    } else {
      // 更新为不全选
      _.forEach(data, item => {
        item.isChecked = false;
      });
    }
  }
  // 列表是否全选
  ctrlCheckAll2(data, checkAllBtn) {
    let that = this;
    let checkList = [];
    if (data !== null) {
      _.forEach(data, item => {
        if (item.isChecked == true) {
          checkList.push(item);
        }
      });
      if (checkList.length == data.length && checkList.length != 0) {
        that.judgeFileType(checkAllBtn, true);
      } else {
        that.judgeFileType(checkAllBtn, false);
      }
    }
  }
  //判断附件类型
  judgeFileType(checkAllBtn, isTrue) {
    switch (checkAllBtn) {
      //  合同扫描
      case 'contractCheckboxAll':
        this.contractCheckboxAll = isTrue;
        break;
      //  合同备忘与协议
      case 'agreementCheckboxAll':
        this.agreementCheckboxAll = isTrue;
        break;
      //  账户类
      case 'accountCheckboxAll':
        this.accountCheckboxAll = isTrue;
        break;
      //  投资类
      case 'investmentCheckboxAll':
        this.investmentCheckboxAll = isTrue;
        break;
      //  报备确认函
      case 'confirmationCheckboxAll':
        this.confirmationCheckboxAll = isTrue;
        break;
      // 业绩考核
      case 'assessmentCheckboxAll':
        this.assessmentCheckboxAll = isTrue;
        break;
      //  其他
      case 'otherCheckboxAll':
        this.otherCheckboxAll = isTrue;
        break;
      //  关联人员
      case 'associatesCheckboxAll':
        this.associatesCheckboxAll = isTrue;
        break;
      //  受托人附件
      case 'enclosureCheckboxAll':
        this.enclosureCheckboxAll = isTrue;
        break;
    }
  }
  // 批量下载
  batchDownload(parameter) {
    let checkbox = [];
    switch (parameter) {
      case 'ContractScanning':
        _.forEach(this.ContractScanning, item => {
          if (item.isChecked) {
            checkbox.push(item.nAttachNo)
          }
        });
        break;
      case "contractAgreement":
        _.forEach(this.contractAgreement, item => {
          if (item.isChecked) {
            checkbox.push(item.nAttachNo)
          }
        });
        break;
      case "accountClass":
        _.forEach(this.accountClass, item => {
          if (item.isChecked) {
            checkbox.push(item.nAttachNo)
          }
        });
        break;
      case "InvestmentClass":
        _.forEach(this.InvestmentClass, item => {
          if (item.isChecked) {
            checkbox.push(item.nAttachNo)
          }
        });
        break;
      case "onfirmation":
        _.forEach(this.onfirmation, item => {
          if (item.isChecked) {
            checkbox.push(item.nAttachNo)
          }
        });
        break;
      case "performanceAssessment":
        _.forEach(this.performanceAssessment, item => {
          if (item.isChecked) {
            checkbox.push(item.nAttachNo)
          }
        });
        break;
      case "Other":
        _.forEach(this.Other, item => {
          if (item.isChecked) {
            checkbox.push(item.nAttachNo)
          }
        });
        break;
      case "Associates":
        _.forEach(this.Associates, item => {
          if (item.isChecked) {
            checkbox.push(item.nAttachNo)
          }
        });
        break;
      case "assignee":
        _.forEach(this.assignee, item => {
          if (item.isChecked) {
            checkbox.push(item.nAttachNo)
          }
        });
        break;
    }
    if (checkbox.length > 0) {
      Util.attachDownload(checkbox);
    } else {
      window['swal']("提示", "请选择文件再下载", "warning");
    }
  }
  // 获取当前激活的附件分类tab
  getFileType(sAttachCode, sAttachType) {
    this.isInitUploadParams = false;
    this.sAttachCode = sAttachCode;
    this.sAttachType = sAttachType;

  }

  // 删除附件
  deleteListAttach(item) {
    let that = this;
    // console.log(item);
    // 如果有关联受托人，有关联基金
    if (item.sLinkPrincipalNo !== null && item.sLinkFundnos !== null) {
      this.doDeleteHistoryAttach(item, '是否确认删除此文件所关联的组合、受托人下的该文件');
    }
    // 如果有关联受托人，没关联基金
    else if (item.sLinkPrincipalNo !== null && item.sLinkFundnos == null) {
      this.doDeleteHistoryAttach(item, '是否确认删除此文件所关联的受托人下的该文件');
    }
    // 如果没有关联受托人，有关联基金
    else if (item.sLinkPrincipalNo == null && item.sLinkFundnos !== null) {
      this.doDeleteHistoryAttach(item, '是否确认删除此文件所关联的组合下的该文件');
    }
    else {
      this.doDeleteHistoryAttach(item, '是否删除附件' + item.sAttachName)
    }

  }


  // 执行删除历史附件操作
  doDeleteHistoryAttach(item, text) {
    let that = this;
    window['swal']({
      "customClass": "product-detail-sweetalert",
      title: "确认?",
      text: text,
      type: "warning",
      showCancelButton: true,
      confirmButtonColor: "rgb(30,185,225)",
      confirmButtonText: "确认",
      cancelButtonText: "关闭",
      closeOnConfirm: true
    }, function () {
      that.fileService.deleteListAttach(item.nAttachNo).subscribe(data => {
        if (data) {
          window['$']('#historyFileModal').modal('hide');
          that.loadFileTree();
          window['swal']("提示", "删除成功", "success");
        }
      });
    });

  }
  // 关闭历史附件modal
  closeHistoryModal() {
    console.log('chufa')
    window['$']('#historyFileModal').modal('hide');
  }
  // ngDoCheck() {
  //   //Called every time that the input properties of a component or a directive are checked. Use it to extend change detection by performing a custom check.
  //   //Add 'implements DoCheck' to the class.
  //   console.log(this.nFundNo)
  //   console.log(this.sAttachType);
  //   console.log(this.sAttachCode);
  // }
  // 编辑附件说明
  editFileDesc(item) {
    item.editDesc = '1';
    item.sFileDesc = _.cloneDeep(item.sAttachDesc);
  }
  // 修改附件说明
  changeFileDesc(item) {
    let that = this;
    let putBody: any = {
      nAttachNo: item.nAttachNo,
      sAttachDesc: item.sFileDesc
    }
    window['swal']({
      title: "提示",
      text: "附件说明是否确定修改为 " + item.sFileDesc + " ?",
      type: "warning",
      showCancelButton: true,
      closeOnConfirm: false,
      confirmButtonText: "确认",
      // confirmButtonColor: "#DD6B55",
      cancelButtonText: "取消",
      showLoaderOnConfirm: false,
    }, function (isConfirm) {
      if (isConfirm) {
        that.fileService.changeFileDesc(putBody).subscribe(data => {
          if (data) {
            window['swal']("成功", "修改成功", "success");
            that.loadFileTree();
          }
        })
      }
    })

  }
  // 取消修改附件说明
  cancelFileDesc(item) {
    item.editDesc = '0';
  }
  // 获取备案机构、受托人、托管人下拉框值
  getDictionary() {
    let that = this;
    this.fileService.getDictionary().subscribe(data => {
      if (data) {
        that.distionary.RECORDORG_TYPE = data.RECORDORG_TYPE;
        that.distionary.LINK_PRINCIPAL_NO = data.LINK_PRINCIPAL_NO;
        that.distionary.TRUSTEE = data.TRUSTEE;
      }
    })
  }
  // 点击表格头排序
  orderData(colName, dataList, dataListName) {
    let listDataAsc = _.orderBy(dataList, [colName], ["asc"]);
    if (JSON.stringify(dataList) == JSON.stringify(listDataAsc)) {
      listDataAsc = _.orderBy(dataList, [colName], ["desc"]);
    }
    switch (dataListName) {
      case 'ContractScanning':
        this.ContractScanning = listDataAsc;
        break;
      case 'contractAgreement':
        this.contractAgreement = listDataAsc;
        break;
      case 'accountClass':
        this.accountClass = listDataAsc;
        break;
      case 'InvestmentClass':
        this.InvestmentClass = listDataAsc;
        break;
      case 'onfirmation':
        this.onfirmation = listDataAsc;
        break;
      case 'performanceAssessment':
        this.performanceAssessment = listDataAsc;
        break;
      case 'assignee':
        this.assignee = listDataAsc;
        break;
      case 'Associates':
        this.Associates = listDataAsc;
        break;
      case 'Other':
        this.Other = listDataAsc;
        break;
      case 'listAttach':
        this.listAttach = listDataAsc;
        break;
      case 'associateList':
        this.associateList = listDataAsc;
        break;
    }
  }
}
